package com.mzw.bizmq;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mzw.common.ErrorCode;
import com.mzw.constant.CommonConstant;
import com.mzw.constant.ExecutionStatus;
import com.mzw.exception.BusinessException;

import com.mzw.manager.AiManager;
import com.mzw.mapper.ChartMapper;
import com.mzw.model.entity.Chart;
import com.mzw.model.entity.User;
import com.mzw.service.ChartService;
import com.mzw.service.EmailService;
import com.mzw.service.UserService;
import com.mzw.utils.SendMessageUtil;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    @Resource
    private EmailService emailService;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ChartMapper chartMapper;

    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message1, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {

        // 获取消息也就是图表ID与原始数据
        String[] strings = message1.split(",", 2);
        String message = strings[0];
        String chartData = strings[1];
        log.info("receiveMessage message = {}", message);
        if (StringUtils.isBlank(message)) {
            // 如果失败，消息拒绝
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        // 先修改图表任务状态为 “执行中”。等执行成功后，修改为 “已完成”、保存执行结果；执行失败后，状态修改为 “失败”，记录任务失败信息。
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(ExecutionStatus.EXECUTION_STATUS_RUN);
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
            return;
        }
        // 调用 AI
        String result = aiManager.doChat(CommonConstant.BI_MODEL_ID, buildUserInput(chart, chartData));
        String[] splits = result.split("【【【【【");

        if (splits.length < 3) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "AI 生成错误");
            return;
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setStatus(ExecutionStatus.EXECUTION_STATUS_SUCCEED);
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
        }

        chartMapper.createTable(Long.toString(chartId));
        String isExists = chartMapper.checkTableExists(Long.toString(chartId));
        if (isExists == null) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "原始数据表创建失败");
            return;
        }
        // 保存数据
        Integer insertNum = chartMapper.insertData(Long.toString(chartId), chartData, genResult);
        if (!(insertNum > 0)) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "原始数据保存失败");
            return;
        }

        Long userId = chart.getUserId();
        User user = userService.getById(userId);
        RLock lock = redissonClient.getLock("lock:sub" + userId);
        // 任务执行成功后扣减次数
        try {
            if (lock.tryLock()) {
                // 在查询一次
                Integer leftNum_ = userService.getById(userId).getLeftNum();
                if (leftNum_ < 1) {
                    channel.basicNack(deliveryTag, false, false);
                    Chart updateNum = new Chart();
                    updateNum.setStatus(ExecutionStatus.EXECUTION_STATUS_FAILED);
                    updateNum.setId(chart.getId());
                    boolean update = chartService.updateById(updateNum);
                    if (!update) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "修改次数不足时状态失败");
                    }
                    handleChartUpdateError(chart.getId(), "剩余次数不足");
                    return;
                }
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.setSql("leftNum = leftNum - 1, totalNum = totalNum + 1");
                boolean isUpdate = userService.update(updateWrapper);
                if (!isUpdate) {
                    channel.basicNack(deliveryTag, false, false);
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "次数扣减失败");
                }
            }
        } catch (BusinessException e) {
            log.info("图表：{}，因为剩余次数不足失败", chart.getId());
        } finally {
            lock.unlock();
        }
        // 向用户发送消息，任务执行成功
        SendMessageUtil.sendMessageSucceed(emailService, user.getUserEmail());
        // 消息确认
        channel.basicAck(deliveryTag, false);
    }


    /**
     * 构建用户输入
     *
     * @param chart
     * @return
     */
    private String buildUserInput(Chart chart, String chartData) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
//        String csvData = chart.getChartData();

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(chartData).append("\n");
        return userInput.toString();
    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(ExecutionStatus.EXECUTION_STATUS_FAILED);
        updateChartResult.setExecMessage(execMessage);
//        SendMessageUtil.sendMessageFail(emailService,
//                userService.getById(chartService.getById(chartId).getUserId()).getUserEmail(),
//                "图表" + chartId + execMessage);
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }
}
